<template>
  <el-card>
    <div class="article-header">
      <el-input
        v-model="searchKeyword"
        placeholder="请输入标题或发布者进行搜索"
        clearable
        class="search-input"
        @input="handleSearch"
      />
      <el-date-picker
        v-model="dateRange"
        type="daterange"
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        class="date-picker"
        style="flex-grow: 0"
        @change="handleSearch"
      />
    </div>
    <div class="article-list">
      <el-row :gutter="20">
        <el-col v-for="item in articleList" :key="item.id" :span="6">
          <el-card
            class="article-item"
            shadow="hover"
            @click="
              router.push({
                name: 'ArticleDetail',
                params: { id: item.id, type: 'public' },
              })
            "
          >
            <!-- 互相关注图标 -->
            <div class="mutual-follow-icon">
              <el-tooltip content="互相关注" v-if="item.mutualFollow">
                <el-icon color="#67C23A" class="icon-animate">
                  <user-filled />
                </el-icon>
              </el-tooltip>
              <el-tooltip content="未互相关注" v-else>
                <el-icon color="#C0C4CC" class="icon-animate">
                  <user />
                </el-icon>
              </el-tooltip>
            </div>
            <div class="article-title" :title="item.title" v-html="item.title"></div>
            <div class="article-meta">
              <span>发布者：{{ item.user.name }}</span>
              <span v-if="item.tags.length"
              >标签：<el-tag v-for="it in item.tags">{{ it.name }}</el-tag>
              </span>
              <span>发布时间：{{ item.published_at }}</span>
            </div>
            <div class="article-stats">
              <div>
                <el-tag type="info">查阅:{{ item.view_count }}</el-tag>
                <el-tag type="success"
                        style="margin-left: 5px"
                >点赞:{{ item.like_count }}</el-tag
                >
              </div>
              <div>
                <!-- 点赞按钮 -->
                <el-tooltip :content="item.is_like ? '取消点赞' : '点赞'">
                  <el-icon
                    style="margin-right: 5px"
                    :class="['icon-btn', { active: item.is_like }]"
                    @click.stop="toggleLike(item)"
                  >
                    <Pointer />
                  </el-icon>
                </el-tooltip>
                <!-- 收藏按钮 -->
                <el-tooltip :content="item.is_favorite ? '取消收藏' : '收藏'">
                  <el-icon
                    :class="['icon-btn', { active: item.is_favorite }]"
                    @click.stop="toggleCollect(item)"
                  >
                    <star />
                  </el-icon>
                </el-tooltip>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <div class="pagination">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="size"
        :current-page="page"
        @current-change="handlePageChange"
      />
    </div>
  </el-card>
  <GiveLikeDialog ref="giveLikeDialogRef" @give-like-success="giveLikeSuccess" />
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import GiveLikeDialog from '@/components/common/giveLikeDialog.vue';
import * as pieceApi from '@/api/piece';
import * as collectApi from '@/api/collection';
import { useDebounceFn } from '@/composables/useDebounceThrottle';

// 文章数据定义
interface Article {
  id: number;
  title: string;
  author: string;
  tags: [{ id: number; name: string }];
  user: { name: string };
  published_at: string;
  views: number;
  followers: number;
  favorite_count: number;
  view_count: number;
  like_count: number;
  comment_count: number;
  created_at: string;
  mutualFollow: boolean;
  is_like: boolean;
  is_favorite: boolean;
  liked: boolean;
  collected: boolean;
}
const router = useRouter();

const size = 50;
const page = ref(1);
const giveLikeDialogRef = ref();
const total = ref(0);
const articleList = ref<Article[]>([]);

const searchKeyword = ref('');
const dateRange = ref<[string, string] | null>(null);

const getPageData = async() => {
  const res = await pieceApi.getArticleByList({
    page: page.value,
    size: size,
    q: searchKeyword.value,
    start_date: dateRange.value ? dateRange.value[0] : undefined,
    end_date: dateRange.value ? dateRange.value[1] : undefined
  });
  console.log('res', res);
  res.data.articles.forEach((article: Article) => {
    article.title = article.title.replace(/<em>/g, '<em style=\'color:greenyellow\'>');
  });
  articleList.value = res.data.articles || [];
  total.value = res.data.pagination.total || 0;
};

getPageData();

function handlePageChange(pages: number) {
  page.value = pages;
  getPageData();
}

function handleSearch() {
  page.value = 1;
  getPageData();
}

// 点赞状态管理
const likingStates = ref<Record<number, boolean>>({}); // 记录每个文章的点赞状态

const { run: debouncedToggleLike } = useDebounceFn(async(item: Article) => {
  const articleId = item.id;

  // 如果正在点赞，直接返回
  if (likingStates.value[articleId]) return;

  likingStates.value[articleId] = true;
  const originalLikeState = item.is_like;
  const originalLikeCount = item.like_count || 0;

  try {
    // 乐观更新：立即更新UI
    item.is_like = !item.is_like;
    item.like_count = item.is_like
      ? originalLikeCount + 1
      : Math.max(0, originalLikeCount - 1);

    await pieceApi.postLike(articleId);
    ElMessage.success(item.is_like ? '已点赞' : '已取消点赞');

    // 重新搜索更新数据
    handleSearch();
  } catch (error) {
    console.error('点赞操作失败:', error);
    // 回滚UI状态
    item.is_like = originalLikeState;
    item.like_count = originalLikeCount;
    ElMessage.error('操作失败，请重试');
  } finally {
    likingStates.value[articleId] = false;
  }
}, 300); // 300ms 防抖，适合点赞操作

const toggleLike = (item: Article) => {
  debouncedToggleLike(item);
};

const itemData = ref<Article | null>();
// 防止重复请求的状态
const isCollecting = ref(false);
/**
 * 防抖处理收藏操作，避免短时间内多次点击导致多次请求
 */
const { run: debouncedToggleCollect } = useDebounceFn(async(item: Article) => {
  if (isCollecting.value) return; // 如果正在请求，直接返回

  isCollecting.value = true;
  itemData.value = item;

  try {
    if (item.is_favorite) {
      // 已收藏，取消收藏
      await collectApi.favorite({ id: item.id });
      giveLikeSuccess();
      // // 更新本地状态
      // item.is_favorite = false
      // item.favorite_count = Math.max(0, item.favorite_count - 1)
    } else {
      if (item.favorite_count) {
        // 有收藏夹，弹出选择收藏夹弹窗
        giveLikeDialogRef.value?.openDialog(item.id);
      } else {
        await collectApi.favorite({ id: item.id });
        giveLikeSuccess();
        // // 更新本地状态
        // item.is_favorite = true
        // item.favorite_count = (item.favorite_count || 0) + 1
      }
    }
  } catch (error) {
    console.error('收藏操作失败:', error);
    // 可以在这里添加错误提示
  } finally {
    isCollecting.value = false;
  }
}, 300);

const toggleCollect = (item: Article) => {
  debouncedToggleCollect(item);
};

// 收藏成功回调
const giveLikeSuccess = () => {
  if (itemData.value) {
    // itemData.value.is_favorite = !itemData.value?.is_favorite
    ElMessage.success(itemData.value?.is_favorite ? '已取消收藏' : '已收藏');
    handleSearch();
  }
};
</script>

<style scoped lang="scss">
.article-header {
  display: flex;
  gap: 16px;
  margin-bottom: 24px;
  align-items: center;
}
.search-input {
  width: 270px;
}
.date-picker {
  width: 260px !important;
}
.article-list {
  margin-bottom: 24px;
}
.article-item {
  margin-bottom: 20px;
  min-height: 160px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  position: relative;
}
.article-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
  width: 100%;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.article-meta {
  font-size: 0.7rem;
  color: #888;
  margin-bottom: 12px;
  display: flex;
  flex-direction: column;
  gap: 4px;
  & span {
    text-align: left;
  }
}
.article-stats {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
}
.pagination {
  display: flex;
  justify-content: center;
}
.mutual-follow-icon {
  position: absolute;
  top: 12px;
  right: 12px;
  z-index: 2;
}
.icon-btn {
  cursor: pointer;
  transition: transform 0.2s, color 0.2s;
  font-size: 22px;
  color: #c0c4cc;
  &:hover {
    transform: scale(1.2);
    color: #409eff;
  }
  &.active {
    color: #f56c6c;
    transform: scale(1.3);
  }
}
.icon-animate {
  transition: transform 0.2s;
}
</style>
